﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using Pro.Common.IoC;

namespace Pro.IoC.Unity
{
    public static class UnityComponentContainerConfiguratorExtensions
    {
        public static void AutoRegister(this UnityComponentContainerConfigurator unityComponentContainerConfigurator)
        {
            IAssemblySourceBuilder assemblySourceBuilder = new AssemblySourceBuilder();
            assemblySourceBuilder.IncludeAssembliesInBaseDirectory(assembly => !AssemblySourceBuilder.ExcludeAssembliesRegex.IsMatch(assembly.FullName));

            IAssemblySource assemblySource = assemblySourceBuilder.Build();
            ITypeSource typeSource = new TypeSource(assemblySource);

            unityComponentContainerConfigurator.UnityContainer.RegisterInstance(typeSource);

            IEnumerable<Type> componentRegistryTypes = typeSource.GetTypes().Where(type => typeof(IComponentRegistry).IsAssignableFrom(type));
            foreach (Type componentRegistryType in componentRegistryTypes)
            {
                unityComponentContainerConfigurator.UnityContainer.RegisterType(typeof(IComponentRegistry), componentRegistryType, componentRegistryType.Name);
            }

            IEnumerable<IComponentRegistry> componentRegistries = unityComponentContainerConfigurator.UnityContainer.ResolveAll<IComponentRegistry>().OrderBy(componentRegistry => componentRegistry.Priority);
            foreach (IComponentRegistry componentRegistry in componentRegistries)
            {
                componentRegistry.Configure(unityComponentContainerConfigurator);
            }
        }
    }
}
